package com.ailianlian.ablecisi.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.ailianlian.ablecisi.R;
import com.ailianlian.ablecisi.constant.ExtrasConstant;
import com.ailianlian.ablecisi.databinding.ActivityCharacterCustomizeBinding;
import com.ailianlian.ablecisi.pojo.entity.AiCharacter;
import com.ailianlian.ablecisi.utils.ImageLoader;
import com.ailianlian.ablecisi.viewmodel.CharacterViewModel;
import com.google.android.material.chip.Chip;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * AI角色定制页面
 */
public class CharacterCustomizeActivity extends AppCompatActivity {

    private ActivityCharacterCustomizeBinding binding;
    private CharacterViewModel viewModel;
    private static final int REQUEST_IMAGE_PICK = 100;
    private Uri selectedImageUri;
    private String characterId = "-1"; // 用于编辑时传入角色ID

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCharacterCustomizeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 设置Toolbar
        setSupportActionBar(binding.toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }

        // 获取传入的角色ID（如果有）
        if (getIntent() != null) {
            characterId = getIntent().getStringExtra(ExtrasConstant.EXTRA_CHARACTER_ID);
            Log.i("CharacterCustomizeActivity", "Received characterId: " + characterId);
        }

        // 初始化ViewModel
        viewModel = new ViewModelProvider(this).get(CharacterViewModel.class);
        setCharacterInfo(characterId);// 设置角色信息（如果是编辑模式）
        setupTypeDropdown();// 设置角色类型下拉菜单
        setupClickListeners();// 设置点击事件
        observeViewModel();// 观察ViewModel数据变化
    }

    private void setCharacterInfo(String characterId) {
        // 如果是编辑模式，加载角色信息
        if (!"-1".equals(characterId)) {
            viewModel.loadCharacterById(characterId);
        }
    }

    private void setupTypeDropdown() {
        List<String> types = viewModel.getCharacterTypes();
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this,
                android.R.layout.simple_dropdown_item_1line,
                types
        );
        ((AutoCompleteTextView) binding.dropdownType).setAdapter(adapter);
    }

    private void setupClickListeners() {
        // 更换头像按钮
        binding.buttonChangeAvatar.setOnClickListener(v -> {
            openImagePicker();
        });

        // 添加自定义兴趣按钮
        binding.buttonAddInterest.setOnClickListener(v -> {
            String customInterest = binding.editCustomInterest.getText() != null ?
                    binding.editCustomInterest.getText().toString().trim() : "";
            if (!TextUtils.isEmpty(customInterest)) {
                System.out.println("customInterest = " + customInterest);
                addCustomInterestChip(customInterest);
                binding.editCustomInterest.setText("");
            }
        });

        // 创建角色按钮
        binding.buttonCreate.setOnClickListener(v -> {
            createCharacter();
        });
    }

    private void observeViewModel() {
        // 观察加载状态
        viewModel.getIsLoading().observe(this, isLoading -> {
            binding.loadingOverlay.setVisibility(isLoading ? View.VISIBLE : View.GONE);
        });

        // 观察创建成功状态
        viewModel.getCreateSuccess().observe(this, isSuccess -> {
            if (isSuccess) {
                Toast.makeText(this, R.string.character_create_success, Toast.LENGTH_SHORT).show();
                finish();
            }
        });

        // 观察错误信息
        viewModel.getErrorMessage().observe(this, errorMsg -> {
            if (errorMsg != null && !errorMsg.isEmpty()) {
                Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
            }
        });

        viewModel.getCurrentCharacter().observe(this, character -> {
            System.out.println("character = " + character);
            if (character != null) {
                Log.i("CharacterCustomizeActivity", "Loaded character: " + character.getName());
                binding.editName.setText(character.getName());
                ((AutoCompleteTextView) binding.dropdownType).setText(character.getType(), false);
                binding.radioMale.setChecked(character.getGender().equals("男"));
                binding.radioFemale.setChecked(character.getGender().equals("女"));
                binding.radioOther.setChecked(character.getGender().equals("其他"));
                binding.editAge.setText(character.getAge() > 0 ? String.valueOf(character.getAge()) : "");
                if (character.getImageUrl() != null) {
                    ImageLoader.load(this, character.getImageUrl(), binding.imageAvatar);
                }
                binding.editPersonalityDesc.setText(character.getDescription());
                binding.editBackground.setText(character.getBackgroundStory());
                binding.chipGroupInterests.removeAllViews();
                for (String interest : character.getInterests()) {
                    addCustomInterestChip(interest);
                }
                binding.chipGroupPersonality.removeAllViews();
                for (String trait : character.getPersonalityTraits()) {
                    Chip chip = (Chip) getLayoutInflater().inflate(R.layout.chip_custom_interstate, binding.chipGroupPersonality, false);
                    chip.setText(trait);
                    chip.setChecked(true);
                    binding.chipGroupPersonality.addView(chip);
                }
            } else {
                Toast.makeText(this, R.string.character_load_error, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, REQUEST_IMAGE_PICK);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_PICK && resultCode == RESULT_OK && data != null) {
            selectedImageUri = data.getData();
            binding.imageAvatar.setImageURI(selectedImageUri);
        }
    }

    private void addCustomInterestChip(String interest) {
        Chip chip = (Chip) getLayoutInflater().inflate(R.layout.chip_custom_interstate, binding.chipGroupInterests, false);
        chip.setText(interest);
        chip.setCloseIconVisible(true);
        chip.setCloseIconTint(getColorStateList(R.color.chip_close_tint));
        chip.setChecked(true);
        chip.setOnCloseIconClickListener(v -> binding.chipGroupInterests.removeView(chip));
        binding.chipGroupInterests.addView(chip);
    }

    private void createCharacter() {
        AiCharacter aiCharacter = new AiCharacter();

        // 设置基本信息
        aiCharacter.setName(binding.editName.getText().toString().trim());
        aiCharacter.setType(((AutoCompleteTextView) binding.dropdownType).getText().toString().trim());
        
        // 设置性别
        if (binding.radioMale.isChecked()) {
            aiCharacter.setGender(getString(R.string.character_gender_male));
        } else if (binding.radioFemale.isChecked()) {
            aiCharacter.setGender(getString(R.string.character_gender_female));
        } else if (binding.radioOther.isChecked()) {
            aiCharacter.setGender(getString(R.string.character_gender_other));
        }
        
        // 设置年龄
        String ageStr = binding.editAge.getText().toString().trim();
        if (!TextUtils.isEmpty(ageStr)) {
            try {
                aiCharacter.setAge(Integer.parseInt(ageStr));
            } catch (NumberFormatException e) {
                Toast.makeText(this, "年龄设置无效", Toast.LENGTH_SHORT).show();
                aiCharacter.setAge(0);
            }
        }
        
        // 设置头像
        if (selectedImageUri != null) {
            aiCharacter.setImageUrl(selectedImageUri.toString());
        }
        
        // 设置性格特点
        List<String> personalityTraits = new ArrayList<>();
        for (int i = 0; i < binding.chipGroupPersonality.getChildCount(); i++) {
            Chip chip = (Chip) binding.chipGroupPersonality.getChildAt(i);
            if (chip.isChecked()) {
                personalityTraits.add(chip.getText().toString());
            }
        }
        aiCharacter.setPersonalityTraits(personalityTraits);
        
        // 设置性格描述
        aiCharacter.setDescription(binding.editPersonalityDesc.getText().toString().trim());
        
        // 设置兴趣爱好
        List<String> interests = new ArrayList<>();
        for (int i = 0; i < binding.chipGroupInterests.getChildCount(); i++) {
            Chip chip = (Chip) binding.chipGroupInterests.getChildAt(i);
            if (chip.isChecked()) {
                interests.add(chip.getText().toString());
            }
        }
        aiCharacter.setInterests(interests);
        
        // 设置背景故事
        aiCharacter.setBackgroundStory(binding.editBackground.getText().toString().trim());
        
        // 验证角色信息
        String errorMsg = viewModel.validateCharacter(aiCharacter);
        if (errorMsg != null) {
            Toast.makeText(this, errorMsg, Toast.LENGTH_SHORT).show();
            return;
        }
        
        // 显示确认对话框
        new MaterialAlertDialogBuilder(this)
                .setTitle(R.string.character_create)
                .setMessage("确定要创建这个AI角色吗？")
                .setPositiveButton(R.string.confirm, (dialog, which) -> {
                    viewModel.createCustomCharacter(aiCharacter);
                })
                .setNegativeButton(R.string.cancel, null)
                .show();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }
} 